﻿#region Copyright

// All Material Copyright © 2010 Dynamic Concepts Development Corp., All Rights Reserved.
//      Portions Copyright © 1984-2009 Dynamic Concepts Development Corp., All Rights Reserved.
// For further information please contact: SoftwareSupport@dynconcepts.com
// Dynamic Concepts Development Corp.  311 W 57th St. Suite #422, New York, NY 10019

#endregion

#region Using References

using System;

#endregion

namespace DynConDevCorp.OpenArch.SupportLibrary.Serialization
{
    internal class ByConvertReaderWriter : IReaderWriter
    {
        #region Constructors

        public ByConvertReaderWriter(Type dataType)
        {
            r_DataType = dataType;
        }

        #endregion

        #region Public Properies and Indexers

        public Type DataType
        {
            get { return r_DataType; }
        }

        #endregion

        #region Public Methods

        public object ConvertFromString(string src)
        {
            if (src == String.Empty)
                return null;
            object result = Convert.ChangeType(src, r_DataType);
            if (!r_DataType.IsAssignableFrom(result.GetType()))
            {
                throw new Exception();
            }
            return result;
        }

        public string ConvertToString(object src)
        {
            if (src == null)
                return String.Empty;

            if (!r_DataType.IsAssignableFrom(src.GetType()))
            {
                throw new Exception();
            }
            string result = (String) Convert.ChangeType(src, typeof (String));
            return result;
        }

        #endregion

        #region Instance Fields (ReadOnly)

        private readonly Type r_DataType;

        #endregion
    }
}